package com.aaa.service.impl;

import com.aaa.dao.MenuMapper;
import com.aaa.entity.Menu;
import com.aaa.service.MenuService;
import com.aaa.vo.MenuTree;
import com.aaa.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: keyboard
 * @description:
 * @author: 闫克起2
 * @create: 2024-03-15 16:55
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    public Result findByStaffId(Integer staffId) {
        //没有层级结构
        List<Menu> menus = menuMapper.selectAll(staffId);
        //1. 获取一级菜单
        List<Menu> first=new ArrayList<Menu>();
        for (Menu m:menus){
            //如果pid==0表示一级菜单
            if(m.getMpid()==0){
                first.add(m);
            }
        }
        //2.如何获取一级菜单下的对应的二级菜单
        for(Menu f:first){
            //存放一级菜单下子菜单
            List<Menu> children=new ArrayList<Menu>();
            for(Menu m:menus){
                if(m.getMpid().equals(f.getMid())){
                    children.add(m);
                }
            }
            f.setChildren(children);
        }

        return new Result(200,"查询左侧菜单成功",first);
    }

    public Result findByRoleId(Integer roleId) {
        //1.查询所有菜单--必须层级结构
        List<Menu> menus=menuMapper.selectAll02();
        //层级关系
        //1. 获取一级菜单
        List<Menu> first=new ArrayList<Menu>();
        for (Menu m:menus){
            //如果pid==0表示一级菜单
            if(m.getMpid()==0){
                first.add(m);
            }
        }
        //2.如何获取一级菜单下的对应的二级菜单
        for(Menu f:first){
            //存放一级菜单下子菜单
            List<Menu> children=new ArrayList<Menu>();
            for(Menu m:menus){
                if(m.getMpid().equals(f.getMid())){
                    children.add(m);
                }
            }
            f.setChildren(children);
        }

        //2.查询当前角色具有的菜单id.
        List<Integer> roleIds=menuMapper.selectMid(roleId);

        return new Result(200,"查询成功",new MenuTree(roleIds,first));
    }

    public Result confirmUpdate(Integer roleId, Integer[] menuIds) {
        //1.删除该角色具有的菜单
       int row1= menuMapper.deleteByRoleId(roleId);

        //2.添加--批量添加
        int row2=  menuMapper.batchInsert(roleId,menuIds);
        if(row1>0&&row2>0){
            return new Result(200,"修改成功",null);
        }
            return new Result(500,"修改失败",null);
    }
}
